package me.zingon.open.bigsmart.queue;

/**
 * @author ztc 1423047407@qq.com
 * @version 1.0
 * @date 2020-8-6 10:25
 */

import me.zingon.open.bigsmart.model.Job;
import me.zingon.open.bigsmart.thread.BucketTimer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * redis zset(有序集合)数据类型
 */
@Component
public class DelayJobBucket {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    JobPoll jobPoll;

    @Autowired
    BucketTimer bucketTimer;

    ZSetOperations zset;

    @PostConstruct
    public void init() {
        zset = redisTemplate.opsForZSet();
    }

    @Value("${redis.prefix.delayJobBucket}")
    String PREFIX;




    public boolean add(Job job) {
        String key = PREFIX + job.getTopic();
        if(zset.add(key, job.getId(), job.getExecTime())) {
            bucketTimer.start(job.getTopic());
            return true;
        }
        return false;
    }

    public Set<String> getReadyJob(String topic){
        String key=PREFIX+topic;
        Set<String> ids = zset.rangeByScore(key,0,System.currentTimeMillis());
        return ids;
    }

    public void rm(String topic,String value){
        String key=PREFIX+topic;
        zset.remove(key,value);
    }


    public Set<String> listTopic(){
        Set<String> keys = redisTemplate.keys(PREFIX+"*");
        return keys.stream().map(k-> k.replace(PREFIX,"")).collect(Collectors.toSet());
    }

}
